package com.bot.utils;

import com.bot.pojo.Anime;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

public class BangumiUtil {
    public static String getTodayAnime() {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 获取当前日期和星期
            TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai")); // 设置时区
            Calendar calendar = Calendar.getInstance();
            int weekday = calendar.get(Calendar.DAY_OF_WEEK);

            // 转换星期格式
            int bgmWeekday = (weekday + 5) % 7;

            // 构造API
            HttpGet httpGet = new HttpGet("https://api.bgm.tv/calendar");
            httpGet.setHeader("User-Agent", "BotApp/1.0 (by my_bot@example.com)"); // Bangumi要求必须设置User-Agent

            //  发送请求并处理响应  先转化为字符串 然后用fastJSON解析
            HttpResponse response = httpClient.execute(httpGet);
            String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
//            System.out.println(responseBody);

            // 解析JSON数据
            JSONArray weekData = JSON.parseArray(responseBody);
            if (weekData == null || weekData.isEmpty()) {
                return "今天没有找到新番更新喵~";
            }

            // 查找今天对应的番剧  逐层解析
            List<Anime> animeList = new ArrayList<>();  //用来封装获取到的番剧
            for (int i = 0; i < weekData.size(); i++) {
                JSONObject dayData = weekData.getJSONObject(i);
                JSONObject weekdayObj = dayData.getJSONObject("weekday");
                if (weekdayObj.getIntValue("id") == bgmWeekday) {
                    JSONArray items = dayData.getJSONArray("items");
                    for (int j = 0; j < items.size(); j++) {
                        //item里面每一个都是一个动画
                        //⭐创建动画对象
                        Anime animeObject = new Anime();
                        JSONObject anime = items.getJSONObject(j);
                        animeObject.setCn_name(anime.getString("name_cn"));

                        //获取评分
                    JSONObject rating = anime.getJSONObject("rating");
                    if (rating == null) {
                        animeObject.setScore("null");
                    } else {
                        try {
                            String score = rating.getString("score");
                            animeObject.setScore(score != null && !score.isEmpty() ? score : "null");
                        } catch (Exception e) {
                            animeObject.setScore("暂无评分");
                        }
                    }

                        //获取封面图片
                    try {
                        if (anime.containsKey("images")) {
                            JSONObject images = anime.getJSONObject("images");
                            if (images != null) {
                                if (images.containsKey("large")) {
                                    animeObject.setImageUrl(images.getString("large"));
                                } else if (images.containsKey("common")) {
                                    animeObject.setImageUrl(images.getString("common"));
                                }
                            }
                        }
                    } catch (Exception e) {
                        // 忽略图片获取失败的异常
                        animeObject.setImageUrl(null);
                    }

                        //中文名为空的话取原名
                    try {
                        if (animeObject.getCn_name() == null || animeObject.getCn_name().isEmpty()) {
                            String originalName = anime.getString("name");
                            animeObject.setCn_name(originalName != null ? originalName : "未知番剧");
                        }
                    } catch (Exception e) {
                        animeObject.setCn_name("未知番剧");
                    }
                        animeList.add(animeObject);
                    }
                    break;
                }
            }

            // 6. 格式化结果
            if (animeList.isEmpty()) {
                return "今天没有新番更新喵~";
            } else {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("今日新番更新\n\n");
                for (int i = 0; i < animeList.size(); i++) {
                    Anime anime = animeList.get(i);
                    stringBuilder.append("【").append(i + 1).append("】 ")
                            .append(anime.getCn_name()).append("\n");
                    // 评分放在下一行，右对齐显示（使用8个空格缩进）
                        String score = anime.getScore();
                        if (score == null || score.isEmpty() || "null".equals(score)) {
                            score = "null";
                        }
                        stringBuilder.append("                                ").append("bgm：").append(score).append("\n");
                    
                    // 添加封面图片信息（用于后续处理）
                    if (anime.getImageUrl() != null && !anime.getImageUrl().isEmpty()) {
                        stringBuilder.append("图片: ").append(anime.getImageUrl()).append("\n");
                    }
                    stringBuilder.append("\n"); // 每个番剧之间空一行
                }
                stringBuilder.append("到点了，该看番了喵🥰🥰🥰~");
                return stringBuilder.toString();
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "获取新番信息时出错喵~";
        }
    }


    /**
     * 搜索角色
     * @param characterName
     * @return
     */
    public static String searchAnimeCharacter(String characterName) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 构造API请求URL
            String apiUrl = "https://api.bgm.tv/v0/search/characters";

            //POST请求头
            HttpPost httpPost = new HttpPost(apiUrl);
            httpPost.setHeader("User-Agent", "BotApp/1.0 (by my_bot@example.com)");
            httpPost.setHeader("Accept", "application/json");
            //创建请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("keyword",characterName);
                //请求内部的嵌套对象
                JSONObject innoRequest = new JSONObject();
                innoRequest.put("nsfw",false);
            requestBody.put("filter",innoRequest);
            StringEntity requestEntity = new StringEntity(requestBody.toJSONString(), StandardCharsets.UTF_8);
            //注入请求体
            httpPost.setEntity(requestEntity);

            //发送请求
            HttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode == 200) {
                String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                JSONObject jsonResponse = JSON.parseObject(responseBody);

                // data数组
                JSONArray data = jsonResponse.getJSONArray("data");

                if (data != null && !data.isEmpty()) {
                    // 第一个匹配结果
                    JSONObject character = data.getJSONObject(0);
                    // 基本信息
                    StringBuilder info = new StringBuilder();
                    // 角色名
                    info.append("角色名: ").append(character.getString("name")).append("\n");

                    // 中文名
                    String chineseName = extractChineseName(character);
                    if (!chineseName.isEmpty()) {
                        info.append("中文名: ").append(chineseName).append("\n");
                    }

                    // 性别
                    String gender = character.getString("gender");
                    if (gender != null) {
                        info.append("性别: ").append(gender.equals("male") ? "男" : "女").append("\n");
                    }

                    // 生日
                    String birthday = extractBirthday(character);
                    if (!birthday.isEmpty()) {
                        info.append("生日: ").append(birthday).append("\n");
                    }

                    //  血型
                    String bloodType = character.getString("blood_type");
                    if (bloodType != null) {
                        info.append("血型: ").append(bloodType).append("\n");
                    }

                    //  简介
                    String summary = character.getString("summary");
                    if (summary != null && !summary.isEmpty()) {
                        info.append("简介: ").append(truncateString(summary, 100)).append("\n");
                    }

                    //  图片
                    JSONObject images = character.getJSONObject("images");
                    if (images != null) {
                        String imageUrl = images.getString("large");
                        if (imageUrl != null && !imageUrl.isEmpty()) {
                            info.append("图片:").append(imageUrl).append("\n");
                        }
                    }
                    return info.toString();
                } else {
                    return "没有找到角色信息喵~";
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            return "搜索时出错喵~";
        }
        return "未找到数据";
    }

    // 截断过长的字符串
    private static String truncateString(String text, int maxLength) {
        if (text == null) return "";
        if (text.length() <= maxLength) return text;
        return text.substring(0, maxLength) + "...";
    }

    // 提取中文名
    private static String extractChineseName(JSONObject character) {
        JSONArray infobox = character.getJSONArray("infobox");
        if (infobox != null) {
            for (int i = 0; i < infobox.size(); i++) {
                JSONObject item = infobox.getJSONObject(i);
                if ("简体中文名".equals(item.getString("key"))) {
                    Object value = item.get("value");
                    if (value instanceof String) {
                        return (String) value;
                    } else if (value instanceof JSONArray) {
                        JSONArray values = (JSONArray) value;
                        if (!values.isEmpty()) {
                            JSONObject firstItem = values.getJSONObject(0);
                            return firstItem.getString("v");
                        }
                    }
                }
            }
        }
        return "";
    }

    // 提取生日
    private static String extractBirthday(JSONObject character) {
        Integer birthYear = character.getInteger("birth_year");
        Integer birthMon = character.getInteger("birth_mon");
        Integer birthDay = character.getInteger("birth_day");

        if (birthMon == null && birthDay == null) {
            return "";
        }

        StringBuilder birthday = new StringBuilder();
        if (birthYear != null) {
            birthday.append(birthYear).append("年");
        }
        if (birthMon != null) {
            birthday.append(birthMon).append("月");
        }
        if (birthDay != null) {
            birthday.append(birthDay).append("日");
        }
        return birthday.toString();
    }

}
